package br.com.insejeccg.util.bean.convert;

import java.lang.reflect.Array;
import java.util.Collection;
import java.util.Map;

import org.apache.commons.beanutils.ConversionException;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.Converter;

import br.com.insejeccg.util.bean.BeanHelperUtil;


/**
 * Faz a conver��o de Objetos em String. Faz um trim() da string
 *
 */
@SuppressWarnings("unchecked")
public class StringArrayConverter implements Converter {
    private String[] defaultValue;

    /**
    * Create a {@link Converter} that will throw a {@link ConversionException}
    * if a conversion error occurs.
    */
    public StringArrayConverter() {
        this.defaultValue = null;
    }

    /**
     * Create a {@link Converter} that will return the specified default value
     * if a conversion error occurs.
     *
     * @param defaultValue The default value to be returned
     */
    public StringArrayConverter(final String[] defaultValue) {
        this.defaultValue = defaultValue;
    }

    /**
     * Convert the specified input object into an output object of the
     * specified type.
     *
     * @param type Data type to which this value should be converted
     * @param value The input value to be converted
     *
     * @exception ConversionException if conversion cannot be performed
     *  successfully
     */
    public Object convert(Class type, Object value) {
        // Deal with a null value
        if (value == null) {
            return (defaultValue);
        }

        // Deal with the no-conversion-needed case
        if (value instanceof String[]) {
            return (value);
        }

        String[] resp = (String[]) defaultValue;

        if (value.getClass().isArray()) {
            resp = convertToArrayString(value);
        }

        if (value instanceof Collection) {
            resp = convertToArrayString(((Collection) value).toArray());
        }

        if (value instanceof Map) {
            resp = convertToArrayString(((Map) value).values().toArray());
        }

        Converter converterString = BeanHelperUtil.lookup(String.class);
        resp = new String[] {
                (String) converterString.convert(String.class, value)
            };

        return resp;
    }

    private String[] convertToArrayString(Object value) {
        if (value.getClass().isArray()) {
            int tam = Array.getLength(value);
            String[] resp = new String[tam];

            for (int i = 0; i < tam; i++) {
                resp[i] = ConvertUtils.convert(Array.get(value, i));
            }
            
            return resp;
        }

        return defaultValue;
    }
}
